package com.yjd.pub.org.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yjd.comm.base.dao.IBaseDao;
import com.yjd.comm.base.enums.DbWREnums;
import com.yjd.comm.base.model.IntroDetailModel;
import com.yjd.comm.base.model.PagerModel;
import com.yjd.comm.base.service.impl.BaseServiceImpl;
import com.yjd.comm.enums.ReferenceTypeEnum;
import com.yjd.comm.merchant.model.MerchantChangeLogsModel;
import com.yjd.comm.merchant.service.IMerchantChangeLogsService;
import com.yjd.comm.org.model.OrganizationModel;
import com.yjd.comm.org.service.IOrganizationService;
import com.yjd.comm.project.model.ProjectModel;
import com.yjd.comm.system.util.SysParamUtil;
import com.yjd.comm.tag.service.ITagRelevanceService;
import com.yjd.comm.util.FrameUtil;
import com.yjd.comm.util.StagesRateUtils;
import com.yjd.comm.util.StringUtil;
import com.yjd.comm.vo.Constant;
import com.yjd.pub.base.dao.IIntroDetailDao;
import com.yjd.pub.org.dao.IOrganizationDao;
import com.yjd.pub.project.dao.IProjectDao;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * <b>description</b>：机构业务实现<br>
 * <b>time</b>：2017-06-27 08:54:35 <br>
 * <b>author</b>：  yangchangyan@yijiedai.com
 */
@Service("organizationService")
public class OrganizationServiceImpl extends BaseServiceImpl implements IOrganizationService {

    /**
     * 插入
     *
     * @param model
     * @return
     * @throws Exception
     */
    public OrganizationModel insert(OrganizationModel model) throws Exception {
        return this.organizationDao.insertModel(model, true);
    }

    /**
     * 更新
     *
     * @param model
     * @return
     * @throws Exception
     */
    public int update(OrganizationModel model) throws Exception {
        return this.organizationDao.updateModel(model, true);
    }

    @Override
    public int createOrUpdate(OrganizationModel org, String orgDetail, String[] tags) throws Exception {

        Long currentTime = FrameUtil.getTime();

        // 创建机构详情
        IntroDetailModel detail = new IntroDetailModel();
        detail.setContent(orgDetail);
        detail.setRef_type(ReferenceTypeEnum.ORGANIZATION.getCode());
        detail.setLast_update_time(currentTime);
        if(null == org.getDetail_id()){
            detail.setCreate_time(currentTime);
            detail = introDetailDao.insertModel(detail, true);
        }else{
            detail.setDetail_id(org.getDetail_id());
            introDetailDao.updateModel(detail, true);
        }

        // 创建机构基本信息
        if(null == org.getIs_used()){
            org.setIs_used(0); // 默认不启用
        }
        if(null == org.getIs_spread()){
            org.setIs_spread(0); // 默认不推广
        }

        //机构分期期数配置
        if(StringUtil.isEmpty(org.getLimit_config())){
            String period = SysParamUtil.getValue(Constant.SysParamKeyEnum.MFQ_PERIODS_CONFIG);
            org.setLimit_config(period);
        } else {
            String period = org.getLimit_config();
            List<Integer> periodsList = StringUtil.getObject(period,List.class);
            Collections.sort(periodsList);
            org.setLimit_config(JSON.toJSONString(periodsList));
        }

        org.setDetail_id(detail.getDetail_id());
        org.setLast_update_time(currentTime);
        if(null == org.getOrg_id()){
            org.setCreate_time(currentTime);
            org = organizationDao.insertModel(org, true);
        }else {
            organizationDao.updateModel(org, true);
        }

        if(null != tags && tags.length > 0) {
            tagRelevanceService.updateTagRelevance(tags, org.getOrg_id(), ReferenceTypeEnum.ORGANIZATION);
        }

        return 1;
    }

    /**
     * 根据id删除
     *
     * @param org_id
     * @return
     * @throws Exception
     */
    public int delete(long org_id) throws Exception {
        Map<Object, Object> paramMap = new HashMap<Object, Object>();
        paramMap.put("org_id", org_id);
        return this.organizationDao.deleteModel(paramMap, true);
    }

    /**
     * 搜索结构列表
     *
     * @param param
     * @return
     * @throws Exception
     */
    @Override
    public PagerModel getOrgListByKeys(Map<String, Object> param) throws Exception {
        return this.getPageModel(param, "getOrgListByKeys", DbWREnums.READ);
    }

    /**
     * 快速分期查询机构列表
     *
     * @param param
     * @return
     * @throws Exception
     */
    @Override
    public List<OrganizationModel> getBillStagesOrgListByKeys(Map<String, Object> param) throws Exception {
        return organizationDao.getBillStagesOrgListByKeys(param);
    }

    @Override
    public Map<Long, String> allOrgAndName() throws Exception {
        List<OrganizationModel> orgs = organizationDao.getModelList(FrameUtil.newHashMap(), false);
        Map<Long, String> orgids = new HashMap<Long, String>();
        for (OrganizationModel org : orgs) {
            orgids.put(org.getOrg_id(), org.getOrg_name());
        }
        return orgids;
    }

    @Override
    public List<Long> queryAllOrgCity(Map<String, Object> param) throws Exception {
        return organizationDao.queryAllOrgCity(param);
    }

    @Override
    public int updateMap(Map param) throws Exception {
        return organizationDao.updateByMap(param, true);
    }

    /**
     * 商户端更新机构期数
     *
     * @param limitList
     * @return
     * @throws Exception
     */
    @Override
    public int updateOrgLimit(Long org_id, List<Integer> limitList) throws Exception {
        if (limitList == null || org_id == null) {
            FrameUtil.throwBaseException1("请求参数不能空");
        }

        // 排序一下，默认升序
        Collections.sort(limitList);

        Long currtime = FrameUtil.getTime(null);
        FrameUtil.newHashMap("org_id", org_id, "limit_config", JSON.toJSONString(limitList), "last_update_time", currtime);
        if (organizationDao.updateByMap(FrameUtil.newHashMap("org_id", org_id, "limit_config", JSON.toJSONString(limitList), "last_update_time", currtime), true) != 1) {
            FrameUtil.throwBaseException1("商户分期期数更新失败");
        }

        // 更新了机构期数后，同步更新该机构下所有项目的分期配置
        List<ProjectModel> updateProjects = new ArrayList<ProjectModel>();
        List<ProjectModel> projectModels = projectDao.getModelList(FrameUtil.newHashMap("org_id", org_id), true);
        ProjectModel p = null;
        Map latestRate = null;
        for(ProjectModel pm : projectModels){
            Map<Integer, Double> currentRateConfig = new HashMap<Integer, Double>();
            if (StringUtil.isNotEmpty(pm.getRate_config())){
                currentRateConfig = JSON.parseObject(pm.getRate_config(), new TypeReference<Map<Integer, Double>>(){});
            }
            p = new ProjectModel();
            p.setProject_id(pm.getProject_id());
            p.setWhere_version(pm.getVersion());
            latestRate = new HashMap();
            for(Integer limit: limitList){
                String rate = "0.0";
                if(currentRateConfig.containsKey(limit)){
                    rate = currentRateConfig.get(limit).toString();
                }else{
                    Constant.SysParamKeyEnum sysParamKeyEnum = StagesRateUtils.getSysParamKeyEnum(limit);
                    if(null != sysParamKeyEnum){
                        rate = SysParamUtil.getValue(sysParamKeyEnum);
                    }
                }
                latestRate.put(limit.toString(), rate);
            }
            p.setRate_config(JSON.toJSONString(latestRate));
            updateProjects.add(p);
        }

        if(updateProjects.size() > 0 ){
            if(projectDao.updateBatch(updateProjects, true) != updateProjects.size()){
                FrameUtil.throwBaseException1("系统繁忙请稍后重试。");
            }
        }

        String context = "商户更新分期期数为：" + JSON.toJSONString(limitList);
        merchantChangeLogsService.insert(new MerchantChangeLogsModel(org_id, context, currtime));
        return 1;
    }

    @Resource
    private ITagRelevanceService tagRelevanceService;

    @Resource
    private IIntroDetailDao introDetailDao;

    @Resource
    private IOrganizationDao organizationDao;

    @Resource
    private IProjectDao projectDao;

    @Resource
    private IMerchantChangeLogsService merchantChangeLogsService;

    @Override
    public IBaseDao getBaseDao() {
        return this.organizationDao;
    }

}
